<template>
  <div class="full-height bg-white page-content content padding-20 add-edit-maintenance-plan scrollbar">
    <div class="plan-title ">计划编号：{{detailData.scheduleNo}}</div>
    <!-- 设备信息 -->
    <q-form @submit="onSubmit"
            greedy
            @reset="onReset"
            ref="myForm"
            class="dialog-content form-inline block no-padding full-height">
      <div style="height:calc(100% - 40px)" class="overflow-hidden-x scrollbar">
        <components is="deviceInfo" title="设备信息" @getDevice="getDevice" ref="deviceInfo"></components>
        <q-separator  class="qa-line"/>
        <maintenance-info title="保养信息"  ref="maintenanceInfo">
          <part-table slot="part" ref="partTableRef"></part-table>
        </maintenance-info>
      </div>
      <q-separator style="flex: 0"/>
      <div class="dialog-footer text-center margin-t-10">
          <q-btn outline label="取消" color="primary" type="reset" class="q-mr-md"/>
          <q-btn unelevated label="确认" color="primary" type="submit"/>
        </div>
    </q-form>
    <q-inner-loading :showing="isLoading" style="z-index: 99">
      <q-spinner-gears size="50px" color="primary" />
    </q-inner-loading>
  </div>
</template>
<script>
import deviceInfo from './common/device-info'
import { mapGetters, mapMutations } from 'vuex'
import _ from 'lodash'
import maintenanceInfo from './common/maintenance-info'
import { getScheduleById, editMaintenanceSchedule } from 'src/boot/maintenance/maintenance-plan'
import moment from 'moment'
import PartTable from '../../spare/parts-list/part-table'
export default {
  name: 'edit-maintenance-plan',
  components: {
    PartTable,
    deviceInfo,
    maintenanceInfo
  },
  data () {
    return {
      isLoading: false,
      deviceList: [], // 设备列表
      cloneData: [], // 克隆新数据
      workShopId: null, // 车间id
      shiftsId: null,
      detailData: {}
    }
  },
  computed: {
    isEdit () {
      const member = !_.isNil(this.$route.query.id) && this.$route.name === 'editMaintenancePlan'
      return member
    },
    ...mapGetters(['footprint'])
  },
  watch: {
    isEdit: {
      handler (newPro) {
        if (newPro) {
          this.$nextTick(() => {
            this.getDetailData()
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    refreshData () {
      // 刷新数据
      this.cloneData = []
      this.deviceList = []
      this.detailData = {}
      this.workShopId = null
      this.shiftsId = null
      this.$refs.deviceInfo.refreshData()
      this.$refs.maintenanceInfo.refreshData()
    },
    // 时间是否处于今天之前
    isBeforeNewDate (date) {
      const startDay = moment(new Date(new Date().setHours(0, 0, 0, 0)))
      const endDay = moment(date)
      let diff = endDay.diff(startDay, 'days')
      return diff < 0
    },
    onSubmit () {
      const deviceIds = this.deviceList.map(v => v.id)
      const partData = this.$refs.partTableRef.tableData
      const params = {
        ...this.uniqDeviceData(deviceIds),
        ...this.$refs.maintenanceInfo.setData(),
        spareParts: partData.map(v => {
          return {
            count: v.count,
            sparePartId: v.id
          }
        })
      }
      if (_.isEmpty(this.deviceList)) {
        this.$message.warning('请添加设备')
        return
      }
      if (_.isEmpty(params.assignedDate)) {
        this.$message.warning('请选择派单时间')
        return
      }
      if (params.assignedCriteria === 2 && !params.assignedOperatorIds.length) {
        this.$message.warning('请选择指定人员')
        return
      }
      if (_.isEmpty(params.programId)) {
        this.$message.warning('请添加保养项目')
        return
      }
      if (this.isBeforeNewDate(params.startDate)) {
        this.$message.warning('编辑计划，请重新设置保养开始日期')
        return
      }
      this.onEditPlan(params)
    },
    // 获取设备列表
    getDevice (val) {
      this.deviceList = val
      const member = _.get(val[0], 'workShopId', '')
      if (this.workShopId === member && this.workShopId !== '') return
      this.workShopId = member
      this.$refs.maintenanceInfo.getShiftsList(this.workShopId, this.shiftsId)
      this.shiftsId = null
    },
    // 处理设备编辑信息
    uniqDeviceData (val) {
      const member = this.cloneData.map(v => v.id)
      const deviceIds = _.difference(val, member) // 新增的数据
      const delDeviceIds = member.filter(v => _.difference(member, val).includes(v))
      return {
        deviceIds,
        delDeviceIds
      }
    },
    onReset () {
      const footprint = this.footprint.filter(v => !v.link.includes('edit-maintenance-plan'))
      this.set_footprint(footprint)
      this.$router.push({ path: `/main/repair/maintenance-plan` })
    },
    // edit
    async onEditPlan (params) {
      try {
        this.isLoading = true
        const ret = await editMaintenanceSchedule(params.id, params)
        if (ret.success) {
          this.isLoading = false
          this.$message.success('编辑成功')
          this.onReset()
        }
      } catch (error) {
        this.isLoading = false
      }
    },
    // 获取详情data
    getDetailData () {
      const id = this.$route.query.id
      this.refreshData()
      this.isLoading = true
      getScheduleById(id).then((result) => {
        this.isLoading = false
        const ret = result.data
        this.detailData = ret
        this.cloneData = _.cloneDeep(ret.devices)
        // 获取设备信息 指派方式为当班操作工 获取班次
        this.shiftsId = _.isUndefined(ret.assignedShiftId) ? null : ret.assignedShiftId
        // 获取保养信息
        this.$refs.maintenanceInfo.initData(ret)
        this.$refs.deviceInfo.initData(ret.devices)
        // 备件清单
        this.$refs.partTableRef.initData(ret.spareParts)
      }).catch((err) => {
        this.isLoading = false
        console.log(err)
      })
    },
    ...mapMutations({
      'set_footprint': 'SET_FOOTPRINT'
    })
  },
  mounted () {
  }
}
</script>
<style scoped lang="scss">
.add-edit-maintenance-plan {
  .dialog-footer{
    padding-bottom:10px;
    .btn{
      width:96px;
      min-height: 32px;
      max-height: 32px;
      box-sizing: border-box;
    }
  }
}
</style>
